package org.reference.generic.work;

import org.reference.generic.base.Item;

/**
 * 
 */
public class Machine extends Item {

    /**
     * 
     */
    public Machine() {
    	release();
    }

    private boolean busy;
    private long readyTime;
    private long totalWorkingTime;
    private int  step;
 

    /**
     * 
     */
    private OnCompleteListenner onCompleteListenner;

    /**
     * @param onCompleteListenner
     */
    public void setOnCompleteListenner(OnCompleteListenner onCompleteListenner) {
        this.onCompleteListenner = onCompleteListenner;
    }

    /**
     * @return
     */
    public boolean isBusy() {
        return busy;
    }

    /**
     * @param readyTime
     */
    public void setReadyTime(long readyTime) {
        this.readyTime=readyTime;
    }

    /**
     * @return
     */
    public long getWorkingTime() {
        return totalWorkingTime;
    }

    /**
     * @param step
     */
    public void setStep(int step) {
        this.step = step;
    }

    /**
     * @return
     */
    public int getStep() {
        return step;
    }

    /**
     * @param job
     */
    public void run(Job job) {
    	busy = true;

		setReadyTime(job.getProcessingTime());  //machine ready time에 job processing time 집어 넣음.
 
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					Thread.sleep(Machine.this.readyTime*1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				Machine.this.onComplete();
			}
		}).start();
    }

    /**
     * 
     */
    public void onComplete() {
    	busy = false;
    	totalWorkingTime += readyTime;
    	setValue(String.valueOf(totalWorkingTime));
    	if (onCompleteListenner == null) return;
    	onCompleteListenner.onComplete(this); // 머신 매니저의 onComplete 호출  
    }

	/**
     * 
     */
    public interface OnCompleteListenner {
        /**
         * @param machine
         */
        public abstract void onComplete(Machine machine);

    }

	@Override
	public void release() {
    	busy = false;
    	readyTime = 0;
    	step = 0;
    	totalWorkingTime = 0;
    	setName("MACHINE");
    	setValue(String.valueOf(totalWorkingTime));
		super.release();
	}
}